package net.zoneland.knowledge.config;

import org.apache.lucene.util.NamedThreadFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池初始化配置
 */
@Configuration
public class ThreadPoolConfig {

    /**
     * 工单创建线程池配置
     * @param corePoolSize 核心线程数
     * @param maximumPoolSize 最大线程数
     * @param keepAliveTime 线程空闲时间
     * @param queueCapacity 队列及队列最大任务数
     * @param threadNamePrefix 自定义的线程工厂及名称
     * @return 线程池服务对象
     */
    @Bean(name = "createApplyThreadPoolExecutor")
    public ExecutorService createApplyThreadPoolExecutor(
            @Value("${createWorkApply.threadPool.corePoolSize}") final int corePoolSize,
            @Value("${createWorkApply.threadPool.maximumPoolSize}") final int maximumPoolSize,
            @Value("${createWorkApply.threadPool.keepAliveTime}") final long keepAliveTime,
            @Value("${createWorkApply.threadPool.queueCapacity}") final int queueCapacity,
            @Value("${createWorkApply.threadPool.threadNamePrefix}") final String threadNamePrefix) {
        return new ThreadPoolExecutor(
                corePoolSize, // 核心线程数
                maximumPoolSize, // 最大线程数
                keepAliveTime, // 线程空闲时间
                TimeUnit.SECONDS, // 空闲时间的单位
                new LinkedBlockingQueue<>(queueCapacity), // 队列及队列最大任务数
                new NamedThreadFactory(threadNamePrefix), // 自定义的线程工厂及名称
                new ThreadPoolExecutor.AbortPolicy()); // 拒绝策略
    }

}
